package com.lej.dataservice.club.room

import androidx.room.*
import com.lej.dataservice.club.bean.commercial.CommercialBean


@Dao
interface CommercialDao {
    @get:Query("SELECT * FROM commercialbean")
    val all: List<CommercialBean>

    /**传秒的时间戳*/
    @Query("SELECT * FROM commercialbean WHERE end_timestamp > (:currentTime) AND start_timestamp < (:currentTime)")
    fun validList(currentTime: Long = System.currentTimeMillis() / 1000): List<CommercialBean>

    @Query("SELECT * FROM commercialbean WHERE ad_id = (:adid)")
    fun get(adid: String): CommercialBean

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insertAll(vararg users: CommercialBean)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(users: List<CommercialBean>): List<Long>

    @Query("DELETE FROM commercialbean WHERE ad_id IN (:ad_id)")
    fun deleteAll(ad_id: Array<String>)

    ///删除列表之外的所有
    fun deleteNotContains(list: List<CommercialBean>) {
        deleteAll(all.filterNot { list.any { i -> it.ad_id == i.ad_id } }.map { it.ad_id }.toTypedArray())
    }

    @Update
    fun update(user: CommercialBean)

    @Update
    fun update(users: List<CommercialBean>)

    @Transaction
    fun upsert(objList: List<CommercialBean>) {
        val insertResult: List<Long> = insert(objList)
        val updateList: MutableList<CommercialBean> = ArrayList()
        for (i in insertResult.indices) {
            if (insertResult[i] == -1L) {
                updateList.add(objList[i])
            }
        }

        updateList.forEach {
            it.showTime = get(it.ad_id).showTime
        }
        if (updateList.isNotEmpty()) {
            update(updateList)
        }
    }

    @Delete
    fun delete(user: CommercialBean)

    @Query("delete from commercialbean")
    fun deleteAll()

}